package org.hswebframework.example.crud.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class TopNAggregator<T>  implements Aggregator<T>{

    private Comparator<T> comparator;
    private int limit;

    public TopNAggregator(Comparator<T> comparator,int limit){
        this.comparator=comparator;
        this.limit=limit;
    }

    @Override
    public Object aggregate(Object key, List<T> values) {
        if(null == values || values.size()==0){
            return null;
        }

        List<T> copy = new ArrayList<T>(values);
        Collections.sort(copy,comparator);
        int size = values.size();
        int toIndex = Math.min(limit,size);
        return copy.subList(0,toIndex);

    }
}
